package com.tangyuan.common.util;

import okhttp3.*;
import org.json.JSONObject;

import java.io.*;

public class BaiDuOCRUtil {


    private static final String client_id = "TCjaaqAspuplVZjpR9z8azHk";
    private static final String client_secret = "d1DT0U2cNIr6tXdNuG1qOECYI8gDA8TU";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    // 获取百度试卷错题擦除AccessToken有效期为30天 2024/5/31 上午 11:34 By 少帅
    public static String getAccessToken() throws IOException {

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?client_id="+client_id+"&client_secret="+client_secret+"&grant_type=client_credentials")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String jsonString = response.body().string();

        // 解析 JSON 字符串
        JSONObject jsonObject = new JSONObject(jsonString);

        // 获取具体的参数
        String accessToken = jsonObject.getString("access_token");

        return accessToken;
    }

    public static String getOCRresult(String fileurl,String accessToken) throws IOException {

        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "url="+fileurl+"&line_probability=false&disp_line_poly=false&words_type=handprint_mix&layout_analysis=false");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/remove_handwriting?access_token="+accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();

        JSONObject jsonObject = new JSONObject( response.body().string());
        // 检查是否存在 error_code 键
        if (jsonObject.has("error_code")) {
            return jsonObject.toString();
        }
        String imageProcessedValue = jsonObject.getString("image_processed");
        return imageProcessedValue;
    }
}
